import { asyncRoutes } from '../../router/router';

function hasRole(route, roles) {
  if (route.meta && route.meta.roles) {
    if (roles.some((role) => route.meta.roles.includes(role))) {
      return true;
    }
    return false;
  }
  return true;
}

function getPermissionRoutes(_asyncRoutes, roles) {
  const array = _asyncRoutes.filter((route) => hasRole(route, roles));
  array.forEach((_val) => {
    const val = _val;
    if (val.children) {
      val.children = getPermissionRoutes(val.children, roles);
    }
  });
  return array;
}

const state = {
  addRoutes: null,
};

const mutations = {
  SET_ROUTES(_state, roles) {
    const backup = _state;
    backup.addRoutes = (getPermissionRoutes(asyncRoutes, roles));
  },
  REMOVE_ROUTES(_state) {
    const backup = _state;
    backup.addRoutes = null;
  },
};

const actions = {
  async addRoutes({ commit }, roles) {
    commit('SET_ROUTES', roles);
    return state.addRoutes;
  },
  async removeRoutes({ commit }) {
    commit('REMOVE_ROUTES');
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
